/**
 * Odoo, Open Source Management Solution
 * Copyright (C) 2012-today Odoo SA (<http:www.odoo.com>)
 * <p>
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version
 * <p>
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details
 * <p>
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http:www.gnu.org/licenses/>
 * <p>
 * Created on 22/4/15 11:43 AM
 */
package com.odoo.core.rpc.helper.utils;

import android.text.TextUtils;
import android.util.Log;

import java.util.Locale;

import com.odoo.core.rpc.Odoo;

public class OdooLog {
    public static final String TAG = OdooLog.class.getSimpleName();

    public static void v(Object... args) {
        if (Odoo.DEBUG)
            Log.v(TAG, buildMessage(null, args));
    }

    public static void d(Object... args) {
        if (Odoo.DEBUG)
            Log.d(TAG, buildMessage(null, args));
    }

    public static void e(Object... args) {
        if (Odoo.DEBUG)
            Log.e(TAG, buildMessage(null, args));
    }

    public static void e(Throwable tr, Object... args) {
        if (Odoo.DEBUG)
            Log.e(TAG, buildMessage(null, args), tr);
    }

    private static String buildMessage(String format, Object... args) {
        String msg = (args == null) ? "" : TextUtils.join(", ", args);
        StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace();

        String caller = "<unknown>";
        // Walk up the stack looking for the first caller outside of VolleyLog.
        // It will be at least two frames up, so start there.
        for (int i = 2; i < trace.length; i++) {
            Class<?> clazz = trace[i].getClass();
            if (!clazz.equals(OdooLog.class)) {
                String callingClass = trace[i].getClassName();
                callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1);
                callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1);

                caller = callingClass + "." + trace[i].getMethodName();
                break;
            }
        }
        return String.format(Locale.US, "[%d] %s: %s",
                Thread.currentThread().getId(), caller, msg);
    }

}
